package com.cnswhy.cloud.server.app.controller.customer;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.BeanPlusUtil;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dto.CustomerWechatSaveDTO;
import com.cnswhy.cloud.server.core.entity.Customer;
import com.cnswhy.cloud.server.core.entity.CustomerWechat;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.CustomerWechatService;
import com.cnswhy.cloud.server.core.service.customer.CustomerService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/Wechat")
@Api(tags = "微信账号信息")
@Slf4j
public class CustomerWechatController extends BaseController {

    @Autowired
    private CustomerWechatService customerWechatService;
    @Autowired
    private CustomerService customerService;

    @Autowired
    private RedisService redisService;

    @ApiOperation(value = "查询分页数据", httpMethod = "POST")
    @ApiParam(name = "bo", value = "查询Bo")
    @RequestMapping("/ajaxWechatData")
    @ResponseBody
    public RespVo ajaxBankData(HttpServletRequest request,
                               @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, CustomerWechat bo) {
        log.info("查询微信信息：{} {} {}", JSON.toJSONString(bo), currentPage, currentPage);
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            bo.setCustomerId(loginCustomer.getId());
            QueryWrapper<CustomerWechat> queryWrapper = QueryGenerator.initQueryWrapper(bo);
            queryWrapper.orderByDesc("create_date");
            Page<CustomerWechat> page = new Page<>(currentPage, pageSize);
            IPage<CustomerWechat> pageList = customerWechatService.page(page, queryWrapper);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询查询微信息失败");
            log.error("查询查询微信息失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "保存微信信息", httpMethod = "POST")
    @ApiParam(name = "entity", value = "微信账号实体")
    @RequestMapping("/saveData")
    @ResponseBody
    public RespVo saveData(CustomerWechatSaveDTO entity, HttpServletRequest request) {
        log.info("保存银行信息：{}", JSON.toJSONString(entity));
        RespVo vo = new RespVo();
        Customer customer = new Customer();
        customer.setLoginName(entity.getMobile());
        QueryWrapper<Customer> queryWrapper = QueryGenerator.initQueryWrapper(customer);
        List<Customer> pageList = customerService.list(queryWrapper);
        if (pageList.size() == 0) {
            vo.setCode(RespVo.VALIDATE_ERROR);
            vo.setMessage("未找到该手机号用户");
            return vo;
        } else {
            entity.setCustomerId(pageList.get(0).getId());
        }
        try {
            if (StringUtils.isBlank(entity.getCustomerId().toString())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("openId为空");
                return vo;
            }
            if (StringUtils.isBlank(entity.getRealName())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("姓名为空");
                return vo;
            }
            if (StringUtils.isBlank(entity.getMobile())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("手机号为空");
                return vo;
            }
            if (StringUtils.isBlank(entity.getOpenId())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("openId为空");
                return vo;
            }
            if (StringUtils.isBlank(entity.getSysCode())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("验证码为空");
                return vo;
            }
            if (!checkVerifyCode(entity.getMobile(), entity.getSysCode())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("验证码错误");
                return vo;
            }

            List<CustomerWechat> queryPage = customerWechatService.list(Wraps.<CustomerWechat>lbQ().eq(CustomerWechat::getCustomerId, entity.getCustomerId()));
            if (queryPage != null && queryPage.size() == 1) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("一个账号最多绑定一个微信哦");
                return vo;
            }
            CustomerWechat customerWechat = BeanPlusUtil.toBean(entity, CustomerWechat.class);
            customerWechatService.save(customerWechat);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("保存成功");
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("保存失败");
            log.error("保存失败", e);
        }
        return vo;
    }


    @ApiOperation(value = "解除微信绑定", httpMethod = "POST")
    @ApiParam(name = "mobile", value = "手机号")
    @RequestMapping("/delete")
    @ResponseBody
    public RespVo delete(String mobile) {
        RespVo vo = new RespVo();
        try {
            CustomerWechat customerWechat = new CustomerWechat();
            customerWechat.setMobile(mobile);
            QueryWrapper<CustomerWechat> queryWrapper = QueryGenerator.initQueryWrapper(customerWechat);
            customerWechatService.remove(queryWrapper);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("微信解绑成功");
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("删除失败");
            log.error("删除失败", e);
        }

        return vo;
    }

    public boolean checkVerifyCode(String mobile, String verifyCode) {
        if (org.apache.commons.lang.StringUtils.isBlank(mobile) || org.apache.commons.lang.StringUtils.isBlank(verifyCode)) {
            return false;
        }

        String redisVerifyCode = (String) redisService.get(RedisConstant.PASS_VERIFY_CODE_REDIS_KEY + mobile);
        if (org.apache.commons.lang.StringUtils.isBlank(redisVerifyCode) || !verifyCode.equals(redisVerifyCode)) {
            return false;
        }

        return true;
    }
}
